/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.controller.notification;

import com.alibaba.fastjson2.JSONObject;
import com.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.message.vo.Notice;
import com.je.common.base.message.vo.PushSystemMessage;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.message.rpc.SocketPushMessageRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping(value = "/je/message/myCollection")
public class MyCollectionController extends AbstractPlatformController {

    private Logger logger = LoggerFactory.getLogger(HomeNotificationController.class);
    private static final String TIME = "time";
    private static final String FUNC = "func";
    @Autowired
    private MetaService metaService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SocketPushMessageRpcService socketPushMessageRpcService;

    /**
     * @param
     * @note 保存我的收藏
     * @date
     */
    @RequestMapping(value = "/saveCollection", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult saveCollection(BaseMethodArgument param, HttpServletRequest request) {
        String title = getStringParameter(request, "COLLECTION_SCBT");
        String funcName = getStringParameter(request, "funcName");
        String funcCode = getStringParameter(request, "funcCode");
        String pkValue = getStringParameter(request, "pkValue");
        String tableCode = getStringParameter(request, "tableCode");
        String userId = getStringParameter(request, "userId");
        String deptId = getStringParameter(request, "deptId");
        if (Strings.isNullOrEmpty(userId) || Strings.isNullOrEmpty(deptId)) {
            userId = SecurityUserHolder.getCurrentAccountRealUserId();
            deptId = SecurityUserHolder.getCurrentAccountRealOrgId();
        }
        List<DynaBean> dynaBeanList = metaService.select("JE_MESSAGE_COLLECTION", ConditionsWrapper.builder().eq("COLLECTION_YWSJZJ", pkValue)
                .eq("COLLECTION_SCYHID", userId).eq("COLLECTION_SCYHBMID", deptId));
        if (dynaBeanList != null && dynaBeanList.size() > 0) {
            return BaseRespResult.errorResult("不可以重复收藏！");
        }
        DynaBean dynaBean = new DynaBean("JE_MESSAGE_COLLECTION", false);
        dynaBean.set("COLLECTION_SCBT", title);
        dynaBean.set("COLLECTION_YWSJZJ", pkValue);
        dynaBean.set("COLLECTION_TABLE_CODE", tableCode);
        dynaBean.set("COLLECTION_FUNC_NAME", funcName);
        dynaBean.set("COLLECTION_FUNC_CODE", funcCode);
        dynaBean.set("COLLECTION_SCYHID", userId);
        dynaBean.set("COLLECTION_SCYHBMID", deptId);
        Notice notice = new Notice();
        notice.setPlayAudio(true);
        commonService.buildModelCreateInfo(dynaBean);
        metaService.insert(dynaBean);
        //右上角通知 监听
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "COLLECTION");
        jsonObject.put("type", "MSG_COLLECTION");
        jsonObject.put("data", dynaBean);
        jsonObject.put("notify", notice);
        PushSystemMessage pushSystemMessage = new PushSystemMessage("", String.valueOf(jsonObject));
        pushSystemMessage.setTargetUserIds(Lists.newArrayList(SecurityUserHolder.getCurrentAccountRealUserId()));
        pushSystemMessage.setSourceUserId("系统");
        socketPushMessageRpcService.sendMessage(pushSystemMessage);
        return BaseRespResult.successResult("保存成功！");
    }

    /**
     * @param
     * @note 加载我的收藏
     * @date
     */
    @RequestMapping(value = "/loadGridCollection", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult loadGridCollection(BaseMethodArgument param, HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String deptId = getStringParameter(request, "deptId");
        if (Strings.isNullOrEmpty(userId) || Strings.isNullOrEmpty(deptId)) {
            userId = SecurityUserHolder.getCurrentAccountRealUserId();
            deptId = SecurityUserHolder.getCurrentAccountRealOrgId();
        }
        String keyWord = getStringParameter(request, "keyWord");
        String oderType = getStringParameter(request, "oderType");
        String whereSql = param.getWhereSql();
        whereSql += "AND COLLECTION_SCYHID = '" + userId + "' AND COLLECTION_SCYHBMID = '" + deptId + "'";
        if (StringUtil.isNotEmpty(keyWord)) {
            whereSql += "AND ( COLLECTION_SCBT like '%" + keyWord + "%' OR COLLECTION_FUNC_NAME like '%" + keyWord + "%' )";
        }
        if (StringUtil.isNotEmpty(oderType) && TIME.equals(oderType)) {
            whereSql += " ORDER BY SY_CREATETIME desc";
        }
        if (StringUtil.isNotEmpty(oderType) && FUNC.equals(oderType)) {
            whereSql += " ORDER BY COLLECTION_FUNC_CODE desc";
        }
        ConditionsWrapper wrapper = ConditionsWrapper.builder().table("JE_MESSAGE_COLLECTION").apply(whereSql);
        int pageNum = param.getPage();
        int limit = param.getLimit();
        long count = 0L;
        int currentPage = 0;
        int pages = 0;
        List<DynaBean> list;
        if (limit == -1) {
            list = metaService.select(wrapper);
            count = list.size();

        } else {
            Page page = new Page(pageNum, limit);
            list = metaService.select("JE_MESSAGE_COLLECTION", page, wrapper);
            count = page.getTotal();
            currentPage = page.getCurrent();
            pages = page.getPages();
        }
        JSONObject returnObj = new JSONObject();
        List<HashMap> values = new ArrayList<>();
        for (DynaBean bean : list) {
            values.add(bean.getValues());
        }
        returnObj.put("rows", values);
        returnObj.put("totalCount", count);
        returnObj.put("currentPage", currentPage);
        returnObj.put("pages", pages);
        return BaseRespResult.successResult(returnObj);
    }

    /**
     * @param
     * @note 删除我的收藏
     * @date
     */
    @RequestMapping(value = "/deleteCollection", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult deleteCollection(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = getStringParameter(request, "JE_MESSAGE_COLLECTION_ID");
        String userId = getStringParameter(request, "userId");
        String deptId = getStringParameter(request, "deptId");
        if (Strings.isNullOrEmpty(userId) || Strings.isNullOrEmpty(deptId)) {
            userId = SecurityUserHolder.getCurrentAccountRealUserId();
            deptId = SecurityUserHolder.getCurrentAccountRealOrgId();
        }
        if (StringUtil.isNotEmpty(pkValue)) {
            int num = metaService.delete("JE_MESSAGE_COLLECTION", ConditionsWrapper.builder().eq("JE_MESSAGE_COLLECTION_ID", pkValue));
            return BaseRespResult.successResult(null);
        }
        int num = metaService.delete("JE_MESSAGE_COLLECTION", ConditionsWrapper.builder().eq("COLLECTION_SCYHID", userId).eq("COLLECTION_SCYHBMID", deptId));

        return BaseRespResult.successResult(null);
    }

    /**
     * @param
     * @note 加载我的收藏
     * @date
     */
    @RequestMapping(value = "/loadCollection", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult loadCollection(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = getStringParameter(request, "pkValue");
        String userId = getStringParameter(request, "userId");
        String deptId = getStringParameter(request, "deptId");
        if (Strings.isNullOrEmpty(userId) || Strings.isNullOrEmpty(deptId)) {
            userId = SecurityUserHolder.getCurrentAccountRealUserId();
            deptId = SecurityUserHolder.getCurrentAccountRealOrgId();
        }
        List<DynaBean> dynaBeanList = metaService.select("JE_MESSAGE_COLLECTION", ConditionsWrapper.builder().eq("COLLECTION_YWSJZJ", pkValue)
                .eq("COLLECTION_SCYHID", userId).eq("COLLECTION_SCYHBMID", deptId));
        if (dynaBeanList != null && dynaBeanList.size() > 0) {
            return BaseRespResult.successResult(true,"已收藏！");
        }

        return BaseRespResult.successResult(false,"未收藏！");
    }

}
